#include "mainwindow.h"
#include "thread_class.h"


ElevatorUart1ReadThread::ElevatorUart1ReadThread(MainWindow *mw0)
{
    mw = mw0;
    com_flag = "abnormal";
    uart_fd = Init_serial(mw->elevator_info_uart_1);
    QTimer::singleShot(100,this,SLOT(rec_timeout()));
    QTimer::singleShot(10000,this,SLOT(check_communication_stat()));

    connect(this,SIGNAL(emit_update()),mw0,SLOT(update_info1()));
}

void ElevatorUart1ReadThread::rec_timeout()
{
    if((time_out_flag > 4))
    {
        time_out_flag = 0;
        data_length = OffsetRcv;
        OffsetRcv =0;
        if(data_length > 5)
        {
            //qDebug("get one frame");
            memcpy(data_buf,RcvBuf,data_length);
            QTimer::singleShot(0,this,SLOT(dispose_data()));
        }
    }

    QTimer::singleShot(20,this,SLOT(rec_timeout()));
    time_out_flag++;
    //mw->showFullScreen();

}

void ElevatorUart1ReadThread::dispose_data()
{
    if(!QFile::exists(mw->source_dir))
        unpacked_frame(data_buf,data_length);
}

void ElevatorUart1ReadThread::check_communication_stat()
{

    QTimer::singleShot(3000,this,SLOT(check_communication_stat()));
    if(com_flag == "abnormal")
    {
        mw->up_frame1->hide();
        mw->down_frame1->hide();
        mw->label_floor->hide();
        mw->label_spec_info->hide();
        mw->system_verify_flag_1 = "";

    }

    com_flag = "abnormal";

}

void ElevatorUart1ReadThread::unpacked_frame(unsigned char *p_buf, int d_length)
{

    unsigned char *p_tmp;
    int Len,DataLen;
    int Xor;
    int offset =0 ;
    p_tmp = p_buf;
#if 0
    int i;
    QString str00,str11;
    for(i=0;i<d_length;i++)
    {
        str00.sprintf("0x%x ",*(p_buf+i));
        str11 +=str00;
    }
    qDebug("%s",qPrintable(str11));
#endif
    //qDebug("uart 1 receive data:%d",d_length);
    while(offset<d_length)
    {
    if((p_tmp[offset] == 0x55) && ((p_tmp[offset+1]) == 0xaa))
    {
        DataLen = p_tmp[offset+3]*256+p_tmp[offset+4];
        Len     = DataLen + 6 + offset;
        if(Len <= d_length)
        {
             Xor = CalculateXOR(p_tmp+2+offset,DataLen+3);
             //qDebug("LEN:%d,offset:%d",Len,offset);

             if(Xor == p_tmp[Len-1])
                {
                  if(p_tmp[2+offset] == 0x12)
                  {
                      elevator_info_state.elevator_state=1;
                      elevator_info_state.floor_info=p_tmp[5+offset];
                      elevator_info_state.direction=p_tmp[6+offset];
                      elevator_info_state.spec_info=p_tmp[7+offset];
                      com_flag = "normal";

                   }
                  else if(p_tmp[2+offset] == 0x14)
                  {
                      elevator_info_state.elevator_state=2;
                      elevator_info_state.audio_info=p_tmp[5+offset];
                      //qDebug("prepare floor audio");
                  }
                  else if(p_tmp[2+offset] == 0x11)
                  {
                      if(AES_check(mw->data_src_encrypt,&p_tmp[5]) == true)
                          mw->system_verify_flag_1 ="verify passed";
                      //qDebug("1111111111111111");
                  }
                }
             //qDebug("uart 1 dispose data");
             if(mw->system_verify_flag_1 =="verify passed")
                emit(emit_update());

      }
        offset+=(DataLen+6);
    }
    else
    {
    offset++;

    }
    }



}

void ElevatorUart1ReadThread::run()
{

    int BytesRead;
    int failedcnt=0;
    unsigned char tmp_rcv;

    OffsetRcv = 0;
    while(1)
    {
        if(uart_fd)
        {
            BytesRead = read(uart_fd,&tmp_rcv,READ_BYTES_MAX);
            *(RcvBuf+OffsetRcv) = tmp_rcv;
        }
        else
            BytesRead = 0;

        if(BytesRead>0)
        {
               //qDebug("read uart data:%d", BytesRead);
               mw->encrypt_uart_fd_1 = uart_fd;
               OffsetRcv += BytesRead;
               if(OffsetRcv >= BUF_SIZE/2)
                       OffsetRcv = 0;

               //timer_0->stop();
               //timer_0->start(5);
               //qDebug("uart 2 time_out_flag:%d   OffsetRcv:%d ",*time_out_flag,OffsetRcv);
               time_out_flag = 0;

               failedcnt=0;
          }
        else
        {
            OffsetRcv = 0;
            if(uart_fd)
            {
                tcflush (uart_fd, TCIOFLUSH); //清空收发buffer
                close(uart_fd);
            }
            uart_fd=Init_serial(mw->elevator_info_uart_1);
            if(uart_fd)
                tcflush (uart_fd, TCIOFLUSH); //清空收发buffer
            msleep(500);//读串口失败后，串口一直处于该状态，重新初始化无效，有待解决该问题
            if(++failedcnt > 10)
            {
                qDebug("uart 1 error");
            }


        }


    }
}



ElevatorUart2ReadThread::ElevatorUart2ReadThread(MainWindow *mw0)
{
    mw = mw0;
    com_flag = "abnormal";

    uart_fd = Init_serial(mw->elevator_info_uart_2);
    QTimer::singleShot(100,this,SLOT(rec_timeout()));
    QTimer::singleShot(10000,this,SLOT(check_communication_stat()));

    connect(this,SIGNAL(emit_update()),mw0,SLOT(update_info2()));
}

void ElevatorUart2ReadThread::rec_timeout()
{
    if((time_out_flag > 4))
    {
        time_out_flag = 0;
        data_length = OffsetRcv;
        OffsetRcv =0;
        if(data_length > 5)
        {
            //qDebug("get one frame");
            memcpy(data_buf,RcvBuf,data_length);
            QTimer::singleShot(0,this,SLOT(dispose_data()));
        }
    }

    QTimer::singleShot(20,this,SLOT(rec_timeout()));
    time_out_flag++;

}

void ElevatorUart2ReadThread::dispose_data()
{
    if(!QFile::exists(mw->source_dir))
        unpacked_frame(data_buf,data_length);
}


void ElevatorUart2ReadThread::check_communication_stat()
{

    QTimer::singleShot(3000,this,SLOT(check_communication_stat()));
    if(com_flag == "abnormal")
    {
        mw->up_frame2->hide();
        mw->down_frame2->hide();
        mw->label_floor1->hide();
        mw->label_spec_info1->hide();
        mw->system_verify_flag_2 = "";

    }
    com_flag = "abnormal";

}

void ElevatorUart2ReadThread::unpacked_frame(unsigned char *p_buf, int d_length)
{

    unsigned char *p_tmp;
    int Len,DataLen;
    int Xor;
    int offset =0 ;
    p_tmp = p_buf;
#if 0
    int i;
    QString str00,str11;
    for(i=0;i<d_length;i++)
    {
        str00.sprintf("0x%x ",*(p_buf+i));
        str11 +=str00;
    }
    qDebug("%s",qPrintable(str11));
#endif
    //qDebug("uart 1 receive data:%d",d_length);
    while(offset<d_length)
    {
    if((p_tmp[offset] == 0x55) && ((p_tmp[offset+1]) == 0xaa))
    {
        DataLen = p_tmp[offset+3]*256+p_tmp[offset+4];
        Len     = DataLen + 6 + offset;
        if(Len <= d_length)
        {
             Xor = CalculateXOR(p_tmp+2+offset,DataLen+3);

             if(Xor == p_tmp[Len-1])
                {
                 //qDebug("LEN:%d,offset:%d",Len,offset);

                  if(p_tmp[2+offset] == 0x12)
                  {
                      elevator_info_state.elevator_state=1;
                      elevator_info_state.floor_info=p_tmp[5+offset];
                      elevator_info_state.direction=p_tmp[6+offset];
                      elevator_info_state.spec_info=p_tmp[7+offset];

                      com_flag = "normal";

                   }
                  else if(p_tmp[2+offset] == 0x11)
                  {
                      if(AES_check(mw->data_src_encrypt,&p_tmp[5]) == true)
                          mw->system_verify_flag_2 ="verify passed";
                      //qDebug("1111111111111111");
                  }
                  /*
                  else if(p_tmp[2+offset] == 0x14)
                  {
                      elevator_info_state.elevator_state=2;
                      elevator_info_state.audio_info=p_tmp[5+offset];
                      //qDebug("prepare floor audio");
                  }
                  else if(p_tmp[2+offset] == 0x10)
                  {
                      if(AES_check(mw->data_src_encrypt,&p_tmp[5]) == true)
                          mw->system_verify_flag ="verify passed";
                      //qDebug("1111111111111111");
                  }
                  */
                }
             //qDebug("uart 1 dispose data");
             if((mw->system_verify_flag_2 =="verify passed")&&(mw->elevator_num =="2"))
                emit(emit_update());

      }
        offset+=(DataLen+6);
    }
    else
    {
    offset++;

    }
    }
}

void ElevatorUart2ReadThread::run()
{

    int BytesRead;
    int failedcnt=0;
    OffsetRcv = 0;
    unsigned char tmp_rcv;
    while(1)
    {
        if(uart_fd)
        {
            BytesRead = read(uart_fd,&tmp_rcv,READ_BYTES_MAX);
            *(RcvBuf+OffsetRcv) =tmp_rcv;
        }
        else
            BytesRead = 0;

        if(BytesRead>0)
        {
               //qDebug("read uart data:%d", BytesRead);
               //mw->encrypt_uart_fd = uart_fd;
            mw->encrypt_uart_fd_2 = uart_fd;

               OffsetRcv += BytesRead;
               if(OffsetRcv >= BUF_SIZE/2)
                       OffsetRcv = 0;

               //timer_0->stop();
               //timer_0->start(5);
               //qDebug("uart 2 time_out_flag:%d   OffsetRcv:%d ",*time_out_flag,OffsetRcv);
               time_out_flag = 0;

               failedcnt=0;
          }
        else
        {
            OffsetRcv = 0;
            if(uart_fd)
            {
                tcflush (uart_fd, TCIOFLUSH); //清空收发buffer
                close(uart_fd);
            }
            uart_fd=Init_serial(mw->elevator_info_uart_2);
            if(uart_fd)
                tcflush (uart_fd, TCIOFLUSH); //清空收发buffer
            msleep(500);//读串口失败后，串口一直处于该状态，重新初始化无效，有待解决该问题
            if(++failedcnt > 10)
            {
                qDebug("uart 1 error");
            }


        }


    }
}
